<template>
  <div class="ele-body">
    <a-row :gutter="12">
      <a-col :span="24">
        <div class="ten-height bg-white padding10 box-shadow">
          <div class="table-header">
            <div class="header-left">
              <a-space size="large">
                <a-tree-select
                  v-model:value="where.orgDataCode"
                  placeholder="数据机构"
                  :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                  :treeData="orgidlist"
                  :replaceFields="{label: 'ORG_NAME', key: 'ORG_ID',value: 'ORG_ID',children:'children' }"
                  style="width: 300px"
                >
                </a-tree-select>
                <a-input
                  v-model:value="where.orderId"
                  placeholder="订单号（回车搜索）"
                  @pressEnter="reload"
                  class="search-input"
                >
                  <template #suffix>
                    <search-outlined @click="reload"/>
                  </template>
                </a-input>
                <a-select
                  v-model:value="where.itemCode"
                  placeholder="产品号"
                  style="width: 300px"
                >
                  <a-select-option
                    v-for="item in itemlist"
                    :key="item.ITEMCODE"
                    :value="item.ITEMCODE">
                    {{ item.ITEMCODE + '-' + item.ITEMNAME }}
                  </a-select-option>
                </a-select>
                <a-input
                  v-model:value="where.batchCode"
                  placeholder="批次号（回车搜索）"
                  @pressEnter="reload"
                  class="search-input"
                >
                  <template #suffix>
                    <search-outlined @click="reload"/>
                  </template>
                </a-input>
                <a-range-picker
                  v-model="where.date"
                  @change="onChange"
                  format="YYYY-MM-DD"
                  style="width: 300px"
                />
                <a-select
                  v-model="where.status"
                  showSearch
                  placeholder="订单状态"
                  optionFilterProp="children"
                  style="width: 300px">
                  <a-select-option v-for="item in statuslist" :key="item.key">
                    {{ item.value }}
                  </a-select-option>
                </a-select>
                <a-button type="primary" class="border-radius"
                          @click="reload">查询
                </a-button>
                <a-button type="primary" style="background-color: red; border-color: red" class="border-radius"
                          @click="clear"
                >清空条件
                </a-button
                >
              </a-space>
            </div>
            <div class="header-right">
              <a-space>
                <a-button v-permission="['ADD_ORDER']"  type="primary" class="border-radius" @click="openAddEdit()">
                  <plus-outlined/>
                  新建
                </a-button>
                <a-dropdown>
                  <template #overlay>
                    <a-menu @click="moreClick">
                      <a-menu-item key="1">
                        <ordered-list-outlined/>
                        自定义列
                      </a-menu-item>
                      <!--                      <div>
                                              <a-menu-item key="2">
                                                <delete-outlined style="color: red"/>
                                                删除
                                              </a-menu-item>
                                            </div>-->
                      <div v-permission="['CLOSE_ORDER']">
                        <a-menu-item key="3">
                          <delete-outlined style="color: red"/>
                          关单
                        </a-menu-item>
                      </div>
                    </a-menu>
                  </template>
                  <a-button>
                    更多
                    <small-dash-outlined/>
                  </a-button>
                </a-dropdown>
              </a-space>
            </div>
          </div>
          <div class="table-content">
            <common-table
              :columns="columns"
              :where="where"
              bordered
              rowId="orderId"
              ref="tableRef"
              url="/productionOrder/page"
              :scroll="{ x: 'max-content', y: 'calc(100vh - 240px)' }"
            >
              <template #bodyCell="{ column, record }">
                <!-- 操作 -->
                <template v-if="column.key == 'action'">
                  <a-space>
                    <icon-font
                      type="class"
                      iconClass="icon-button-edit"
                      color="var(--primary-color)"
                      font-size="20px"
                      fontWeight="bold"
                      title="编辑"
                      v-permission="['EDIT_ORDER']"
                      @click="openAddEdit(record)"
                    ></icon-font>
                    <icon-font
                      type="class"
                      iconClass="icon-button-delete"
                      color="red"
                      font-size="20px"
                      fontWeight="bold"
                      title="删除"
                      v-permission="['DELETE_ORDER']"
                      v-if="record.status==1"
                      @click="remove(record)"
                    ></icon-font>
                    <a-button v-permission="['CLOSE_ORDER']" type="primary" style="background-color: red;
                              border-color: red" class="border-radius"
                              @click="Close(record)">关单
                    </a-button>
                    <a-button  v-permission="['MATERIAL_ORDER']" type="primary" class="border-radius"
                              @click="material(record)">物料
                    </a-button>
                  </a-space>
                </template>
              </template>
            </common-table>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-modal
      :visible="materialfalg"
      title="物料详情"
      width="60%"
      :confirm-loading="loading"
      @cancel="colseMaterial()"
    >
      <a-table
        :dataSource="mbomlist"
        :columns="mbomcolumns"
        :rowKey="
          (record, index) => {
            return index
          }
        "
        :pagination="{ defaultPageSize: 5 }"
      >

      </a-table>
      <a-table
        :dataSource="materiallist"
        :columns="materialcolumns"
        :rowKey="
          (record, index) => {
            return index
          }
        "
        :pagination="{ defaultPageSize: 5 }"
      >

      </a-table>
    </a-modal>
    <!-- 自定义列 -->
    <Custom
      v-model:visible="isShowCustom"
      v-if="isShowCustom"
      :data="columns"
      @done="val => (columns = val)"
      :fieldBusinessCode="fieldBusinessCode"
    />

    <!-- 新增编辑弹框 -->
    <ProductionOrderAddEdit v-model:visible="showEdit" v-if="showEdit" :orgidlist="orgidlist"
                            :itemlist="itemlist"
                            :routelist="routelist"
                            :data="current"
                            @done="reload"/>
  </div>
</template>

<script setup name="ProductionOrder">
import {ProductionOrderApi} from './api/ProductionOrderApi';
import {ref, createVNode, onMounted} from 'vue';
import {message, Modal} from 'ant-design-vue/es';
import ProductionOrderAddEdit from './components/production-order-add-edit.vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {CustomApi} from '@/components/common/Custom/api/CustomApi';
import {SysDictTypeApi} from '@/components/DictSelect/api/SysDictTypeApi';
import {Common} from "@/api/Common";

const mbomlist = ref([])
const materiallist = ref([])
const mbomcolumns = ref([
  {
    dataIndex: 'itemCode',
    title: '件号',
    align: 'center',
  }, {
    dataIndex: 'itemSpecifications',
    title: '规格',
    align: 'center',
  }, {
    dataIndex: 'itemStaus',
    title: '状态',
    align: 'center',
  }, {
    dataIndex: 'itemPlanCount',
    title: '计划数量',
    align: 'center',
  },
  {
    dataIndex: 'itemPlanNum',
    title: '根数',
    align: 'center',
  },
])
const materialcolumns = ref([
  {
    dataIndex: 'itemCode',
    title: '件号',
    align: 'center',
  }, {
    dataIndex: 'itemQuanTity',
    title: '数量',
    align: 'center',
  }, {
    dataIndex: 'itemNum',
    title: '根数',
    align: 'center',
  },
  {
    dataIndex: 'unitCode',
    title: '计量单位编码',
    align: 'center',
  }, {
    dataIndex: 'materialCode',
    title: '材料牌号',
    align: 'center',
  }, {
    dataIndex: 'furnaceCode',
    title: '炉批号',
    align: 'center',
  },
])
// 表格配置
const columns = ref([
  {
    key: 'index',
    title: '序号',
    width: 48,
    align: 'center',
    isShow: true,
    hideInSetting: true,
    customRender: ({index}) => tableRef.value.tableIndex + index
  },
  {
    dataIndex: 'orderId',
    title: '订单ID',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'itemCode',
    title: '件号',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'batchCode',
    title: '批次号',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'routeCode',
    title: '工艺路径',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'priority',
    title: '优先级',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'planCount',
    title: '计划数量',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'compCount',
    title: '完成数量',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'qrate',
    title: '合格率',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'planStartTime',
    title: '计划开始时间',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'planEndTime',
    title: '计划结束时间',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'startTime',
    title: '实际开始时间',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'endTime',
    title: '实际完成时间',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true
  },
  {
    dataIndex: 'source',
    title: '来源',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true,
    customRender: ({value}) => {
      if (value == 1) {
        return 'ERP'
      } else {
        return '人工'
      }
    }
  },
  {
    dataIndex: 'kitting',
    title: '已齐套',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true,
    customRender: ({value}) => {
      return initkitting(value)
    }
  },
  {
    dataIndex: 'status',
    title: '订单状态',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true,
    customRender: ({value}) => {
      if (value)
        return value == '1' ? '未确认' : value == 2 ? '已确认' : value == 3 ? '生产中' : value == 4 ? '暂停'
          : value == 5 ? '已完成' : value == 6 ? '手动关单' : value == 7 ? '已发货' : value == 8 ? '使用中' : '使用完成'
    }
  },
  {
    dataIndex: 'itemStatus',
    title: '加工零件状态',
    align: 'center',
    ellipsis: true,
    width: 200,
    isShow: true,
    customRender: ({value}) => {
      var ret = ''
      itemstatuslist.value.forEach(item => {
        if (item.dictCode == value) {
          ret = item.dictName
        }
      })
      return ret
    }
  },
  {
    key: 'action',
    title: '操作',
    align: 'center',
    width: 100,
    fixed: 'right',
    isShow: true
  }
]);
// ref
const tableRef = ref(null);
const orgidlist = ref([]);
const itemlist = ref([]);
const routelist = ref([]);
const statuslist = ref([{key: '1', value: '未确认'}, {key: '2', value: '待开始'}, {key: '3', value: '生产中'}, {
  key: '4',
  value: '暂停'
},
  {key: '5', value: '已完成'}, {key: '6', value: '手动关单'}, {key: '7', value: '已发货'}, {
    key: '8',
    value: '使用中'
  }, {key: '9', value: '使用完成'}]);

// 搜索条件
const where = ref({
  orgDataCode: undefined,
  orderId: '',
  itemcode: undefined,
  batchCode: '',
  date: [],
  begintime: undefined,
  endTime: undefined,
  status: '',
});
const initkitting = (value) => {
  if (value) {
    const arr = value.split(",")
    var retvalue = ''

    if (arr.length == 3) {
      if (arr[0] == 1) {
        retvalue += '原材料,'
      }
      if (arr[1] == 1) {
        retvalue += '刀具,'
      }
      if (arr[2] == 1) {
        retvalue += '工装夹具,'
      }
      return retvalue.substring(0, retvalue.length - 1);
    } else {
      return value;
    }
  }
}
// 是否显示自定义列
const isShowCustom = ref(false);

// 当前行数据
const current = ref(null);

// 是否显示新增编辑弹框
const showEdit = ref(false);
const materialfalg = ref(false);

// 业务标识的编码
const fieldBusinessCode = ref('PRODUCTION_ORDER');
const itemstatuslist = ref([]);

onMounted(() => {
  getDictlist();

});
const getDictlist = () => {
  SysDictTypeApi.getDictListByParams({dictTypeId: '1735960326503501826'}).then(res => {
    itemstatuslist.value = res
  });
  Common.getTreeOrgids().then(res => {
    if (res.success) {
      orgidlist.value = res.data;
    }
  })
  getColumnData();
  Common.getItemList().then(res => {
    if (res.success) {
      itemlist.value = res.data;
    }
  })
  Common.getRouteList().then(res => {
    if (res.success) {
      routelist.value = res.data;
    }
  })
}
const onChange = (date, dateString) => {
  where.value.startTime = dateString[0]
  where.value.endTime = dateString[1]
}
const material = (record) => {
  ProductionOrderApi.material({orderId: record.orderId}).then(res => {
    if (res.bomlist) {
      mbomlist.value = res.bomlist
    }
    if (res.materiallist) {
      materiallist.value = res.materiallist
    }
  });
  materialfalg.value = true
}
const colseMaterial = () => {
  materialfalg.value = false
}

// 获取表格配置
const getColumnData = () => {
  CustomApi.getUserConfig({fieldBusinessCode: fieldBusinessCode.value}).then(res => {
    if (res.tableWidthJson) {
      columns.value = JSON.parse(res.tableWidthJson);
    }
  });
};

// 更多点击
const moreClick = ({key}) => {
  if (key == '1') {
    isShowCustom.value = true;
  } else if (key == '2') {
    batchDelete();
  } else if (key == '3') {
    batchClose();
  }
};

// 点击搜索
const reload = () => {
  tableRef.value.reload();
};

// 清除搜索条件
const clear = () => {
  where.value = {
    orgDataCode: undefined,
    orderId: '',
    itemcode: undefined,
    batchCode: '',
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    date: [],
  };
  reload();
};

// 新增编辑点击
const openAddEdit = record => {
  current.value = record;
  showEdit.value = true;
};

const Close = record => {
  Modal.confirm({
    title: '提示',
    content: '确定要关闭选中的订单管理吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ProductionOrderApi.close({orderId: record.orderId});
      message.success(res.message);
      reload();
    }
  });
};

// 删除单个
const remove = record => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的订单管理吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ProductionOrderApi.delete({orderId: record.orderId});
      message.success(res.message);
      reload();
    }
  });
};

// 批量删除
const batchDelete = () => {
  if (tableRef.value.selectedRowList && tableRef.value.selectedRowList.length == 0) {
    return message.warning('请选择需要删除的订单管理');
  }
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的订单管理吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ProductionOrderApi.batchDelete({batchDeleteIdList: tableRef.value.selectedRowList});
      message.success(res.message);
      reload();
    }
  });
}
// 批量关闭
const batchClose = () => {
  if (tableRef.value.selectedRowList && tableRef.value.selectedRowList.length == 0) {
    return message.warning('请选择需要关闭的订单管理');
  }
  Modal.confirm({
    title: '提示',
    content: '确定要关闭选中的订单管理吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ProductionOrderApi.batchClose({batchDeleteIdList: tableRef.value.selectedRowList});
      message.success(res.message);
      reload();
    }
  });
}
</script>

<style scoped lang="less">
.table-header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.table-content {
  width: 100%;
  height: calc(100% - 50px);
}

:deep(.ant-table-body) {
  min-height: calc(100vh - 240px) !important;
}

.search-input {
  width: 300px;
  border-radius: 5px;
}
</style>
